//
//  FGMainViewController.swift
//  微博
//
//  Created by 陈金田 on 16/12/29.
//  Copyright © 2016年 陈金田. All rights reserved.
//

import UIKit
//主控制器
class FGMainViewController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
     setupChildControllers()
     setupComposeButton()
      
    }

       func composeStatus(){
        print("写微博")

    }
    
   
    //私有控件
     lazy var composeButton : UIButton = UIButton.cz_imageButton("tabbar_compose_icon_add", backgroundImageName: "tabbar_compose_button")
}


//extension 类似于oc中的分类，在swift中可以用来切分代码块，可以把相近功能的函数，放在一个extension 中，便于维护，使用注意，和oc的分类一样，extension 中，不能定义属性，只可定义方法
extension FGMainViewController{
    
       func setupComposeButton(){
        
        tabBar.addSubview(composeButton)
        //设置按钮的位置
        let count : CGFloat = (CGFloat(childViewControllers.count))
        let w = tabBar.bounds.width / count - 1
        composeButton.frame = tabBar.bounds.insetBy(dx: 2 * w, dy: 0)
        
        //按钮监听方法
        composeButton.addTarget(self, action: #selector(composeStatus), for: .touchUpInside)
  
    }
    

     func setupChildControllers(){
        let array = [
            ["clsName" : "FGHomeViewController","title":"首页","imageName" : "home"],
             ["clsName" : "FGMessageViewController","title":"信息","imageName" : "message_center"],
             ["clsName":"UIViewController"],
              ["clsName" : "FGDiscoverViewController","title":"发现","imageName" : "discover"],
               ["clsName" : "FGProfileViewController","title":"我的","imageName" : "profile"],
        ]
        
        var arrayM = [UIViewController]()
        for dict in array {
            arrayM.append(controller(dict: dict))
       }
        
        viewControllers = arrayM
    }
    
    //reture 子控制器
     func controller(dict : [String : String])->UIViewController{
        
        //取得字典内容
        guard let clsName = dict["clsName"],
            let title = dict["title"],
            let imageName = dict["imageName"],
            let cls = NSClassFromString(Bundle.main.namespace + "." + clsName) as? FGBaseViewController.Type
            else{
                
            return UIViewController()
        }
        
        //创建视图控制器
        let vc = cls.init()
        
        vc.title = title
        //设置图像
        vc.tabBarItem.image = UIImage(named: "tabbar_" + imageName)
        vc.tabBarItem.selectedImage = UIImage(named: "tabbar_" + imageName + "_selected")?.withRenderingMode(.alwaysOriginal)
        
        //设置标题字体，大小
        vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName : UIColor.orange], for: .highlighted)
        vc.tabBarItem.setTitleTextAttributes([NSFontAttributeName : UIFont.boldSystemFont(ofSize: 14)], for: UIControlState(rawValue: 0))
        
        let nav = FGNavigationController(rootViewController: vc)
        return nav
    
    }
    
  

}

